if (!$.cookie('token')) {
    window.location.href = './shopunknwo.html'
}

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            goodsid:'',
            typename:"",
            description:"",
            thumbpath:"",
            awards:'',
            awardlink:[],
            thumburl: '',
           

            booklist:[],
            booklist_select_html:[],
            checklist:[],
        };
    } 
    componentDidMount() {
        let {awards} = this.state,awardlink=[],that = this;
     
        getmain(res=>{
            console.log(res)
            if(res.issuccess==1){
                awards=JSON.parse(HtmlUtil.htmlDecodeByRegExp(res.awards));
                console.log(awards)
            if(awards.length>0){
                awards.forEach((x,i)=>{
                    // console.log(x,i);
                    console.log(x.name)
                    awardlink.push(
                        <option key={i} value={x.name}>{x.name}
                         </option>
                    );
                });
            }
        }
            that.setState({awards,awardlink,typename:awards[0].name});

            this.getdetailtypename(awards[0].name);
        })
        

    }
    getdetailtypename(typename){
        
        let booklistlink = [], booklist = [{id:"1",name:"惊悚乐园"},{id:"2",name:"明朝那些事"},{id:"3",name:"鬼喊抓鬼"}];
        if(booklist.length>0){      
            booklist.forEach((x,i)=>{
                booklistlink.push(
                    <option key={i} value={x.id}>{x.name}
                    </option>
                );
            });                   
        }
       
        getawardtypedetail(typename,res=>{
          
            if(res.issuccess==1){
                if(res.data!=null){
                let {description,thumbpath,goodsid} = res.data,booklist_select_html=[],that=this,thumburl="",
                checklist=goodsid.split(',');
                checklist.forEach((x,i)=>{
                    booklist.forEach((y,j)=>{
                        if(x==y.id){
                            booklist_select_html.push(
                                <tr key={booklist_select_html.length}>
                                    <td>{y.id}</td>
                                    <td>{y.name}</td>
                                    <td className='operate'>
                                        {/* <p className='edit' onClick={that.edit.bind(that, x.id)}>编辑</p> */}
                                        <p onClick={that.del.bind(that, x.id)}>删除</p>
                                    </td></tr>)
                        }
                    });
                });
                
                if(thumbpath.indexOf('http')==-1){

                    thumburl=`${API_HEAD}imgs/${thumbpath}`
                    console.log(thumburl);
                }

                
                this.setState({
                    description,
                    thumbpath,
                    thumburl,
                    checklist,
                    booklist_select_html
                });
            }else{
                this.setState({
                    description:'',
                    thumbpath:'',
                    thumburl:'',
                    checklist:[],
                    booklist_select_html:[],
                });
            }
            }else{

                
            }
        });
        this.setState({booklist,booklistlink,bookid:booklist[0].id});
    }

    // console.log(this.state.thum)
    clickupload(e) {
        console.log(e, 'clickupload');
         $('#file').click();

    }



    filechange(e) {
        console.log(e);
        this.setState({
            finishupload: !1,
            uploadword: "上传"
        })
        var that = this;
        var filecode = this.state.filecode;
        console.log(filecode, 'filecode');
        var filedata = $('#file')[0].files[0];

        var reader = new FileReader();
        reader.readAsDataURL(filedata);
        reader.onload = function (e) {
            var base64str = e.target.result;
            that.setState({ thumburl: base64str })
        }
    }

    //

    del_detail_img(e) {
        var that = this;
        if (e == -1) {
            //删除封面图
            this.setState({
                thumburl: '',
            })
            return;
        }

    }


    del_swiper_img(e) {
        var that = this;
        var swiperimg = [];
        var swiperimglist = this.state.swiperimglist;
        swiperimglist.splice(e, 1);
        swiperimglist.forEach((x, i) => {
            swiperimg.push(
                <div className={"detailimg_div index" + i} key={i}>
                    <img key={i} src={x} className="img-responsive" />
                    <img key={"close_" + i} className='closeimg' onClick={that.del_swiper_img.bind(that, i)} src='./src/img_close.png' />
                </div>
            )
        })
        that.setState({
            swiperimg,
            swiperimglist,

        })

    }



    upload() {
        let {thumburl,thumbpath} = this.state;
        if (isBase64(thumburl)) {
            uploadimg(thumburl, res => {
                if (res.issuccess == 1) {
                    thumbpath=res.path;
                } else {
                    alert(res.msg)
                    err = 1
                    return;
                }
            })
        }
        
        this.setState({thumbpath,finishupload:!0});
    }



    submit() {
        var { thumburl,thumbpath, description, checklist, typename ,finishupload} = this.state, err = '';
        // console.log(thumburl,thumbpath, description, checklist, typename);
    
        // console.log(this.state);


        if (thumburl=="") err = '请添加图片';
        if (description == "") err = '请填写描述';
        
        if (!isBase64( thumburl)) err = '请上传图片';
        if(checklist.length==0) err="请添加图书";
    
        if (err.length > 0) {
            alert(err);
            return;
        }

        console.log("嘿嘿",thumbpath,"呵呵",thumburl);

        let goodsid = checklist.join(",");
        let submitdata = { goodsid, typename, description,thumbpath};
        
        awardaoe(submitdata, res => {
            if (res.issuccess == 1) {
                alert('保存成功');
                // window.location.href='./main.html'
            }
        })
    }



    
    ontypenamechange(e){
        this.setState({typename:e.target.value});
        this.getdetailtypename(e.target.value);
    }
    inputchange(e, x) {
        var prop = "description"
        this.setState({
            [prop]: x.target.value
        })
    }
    confirmbook(e){
        let {booklist,booklist_select_html,bookid,checklist}=this.state,that=this;
        if(checklist.indexOf(bookid)>-1){
            alert("请不要重复添加");
            return;
        }
        checklist.push(bookid);      
        if(booklist.length>0){
            booklist.forEach(x => {
                if (x.id == bookid)
                booklist_select_html.push(
                        <tr key={booklist_select_html.length}>
                            <td>{x.id}</td>
                            <td>{x.name}</td>
                            <td className='operate'>
                                {/* <p className='edit' onClick={that.edit.bind(that, x.id)}>编辑</p> */}
                                <p onClick={that.del.bind(that, x.id)}>删除</p>
                            </td></tr>
                    )
                this.setState({checklist,booklist,booklist_select_html})
    
            })
        }
    }
    del() {
        $('#myModal').modal('toggle');
    }
    confirmdel() {
        delgoods(this.state.id, res => {
            if (res.issuccess == 1) {
                window.location.href = './main.html'
            }

        })
    }
    onbookchange(e){
        this.setState({bookid:e.target.value});
    }
    render() {
        let {btntypehtml} = this.state;
        //  <img style={{display:this.state.thumburl.length>0?"block":"none"}} src={this.state.thumburl} className="img-responsive"  /> 

        return (
            <div>
                <Modal content='确定删除吗？' click={this.confirmdel.bind(this)} />
                <div className='content_wrap panel-default content_wrap'>
                    <div className='breadLine '>
                        当前位置 > 大奖作品管理 > {this.state.id == 0 ? "新建" : "编辑"}大奖作品
                    </div>
                    <div className='inputs panel-body'>
                        <h3>{this.state.id == 0 ? "新建" : "编辑"}大奖作品</h3>
                        <div className="input-group">
                            <span className="input-group-addon">大奖作品</span>
                            <select value={this.state.name} onChange={this.ontypenamechange.bind(this)} className="form-control select">
                                {this.state.awardlink}
                            </select>
                        </div>

                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">封面图</span>
                            <input onChange={this.filechange.bind(this)} type='file' id='file' />
                            <div className='img_warp' >
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this)} style={{ display: this.state.thumburl != "" ? "none" : "" }} />
                               {console.log(this.state.thumburl)} 
                                <img style={{ display: this.state.thumburl != ""  ? "block" : "none" }} src={this.state.thumburl} className="img-responsive" />
                                <img className='closeimg thumb' style={{ display: this.state.thumburl != "" ? "block" : "none" }} onClick={this.del_detail_img.bind(this, -1)} src='./src/img_close.png' />
                            </div>
                        </div>

                        <div className="input-group">
                            <span className="input-group-addon">图书列表</span>
                            <select value={this.state.bookid} onChange={this.onbookchange.bind(this)} className="form-control select">
                                {this.state.booklistlink}
                            </select>
                            <button onClick={this.confirmbook.bind(this)} className='btn submit btn-primary center ' style={{marginLeft:"30px"}}>确定添加</button>
                            <table className="table table-hover ">
                            <thead>
                                <tr>
                                    <th>图片</th>
                                    <th>名称</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {this.state.booklist_select_html}
                            </tbody>
                        </table>
                        </div>
                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">商品描述</span>
                            <textarea id='describe' onChange={this.inputchange.bind(this, 3)} value={this.state.description} style={{ height: "30vh" }} className="form-control" placeholder='请输入商品描述' rows="3"></textarea>
                        </div>

                        <div className='btns_bottom center'>
                            <div style={{ display: this.state.thumburl.length > 0 ? "flex" : "none" }} className='btn_upload'>
                                {/* <button onClick={this.upload.bind(this)}
                                    className={`btn add btn-${this.state.finishupload ? "success" : "primary"} center w20`} id='btnimg_save'>{this.state.uploadword}</button> */}

                            </div>
                            <button className='btn add btn-primary center w20' onClick={this.submit.bind(this)} id='btnimg_save'>保存</button>
                            <button onClick={this.upload.bind(this)} className={`btn addpart btn-${this.state.finishupload ? 'success' : 'primary'} center w20`} >{this.state.finishupload ? '上传成功' : '上传图片'}</button>
                        </div>
                    </div>
                </div>
            </div>

        )
    }
}


ReactDOM.render(
    <div>
        <TopLine />
        <LeftMenu code='3' />
        <LeftMenu code='award' />
        <Main />
    </div>
    , $('.container')[0]
)